package com.jintoufs.util.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaoemo on 2017/11/22.
 */
public class CurrencyApi {
    private static String URL = "http://api.k780.com/?app=finance.rate&appkey=29747&sign=1c9e056e5989acbf18037a113f48c9bd";

    /***
     * 获取最新的汇率
     * @param scur 源币种
     * @param tcur 目标币种
     * @return 汇率
     */
    public static double getCurrentRate(String scur, String tcur) {
        double rate = 0.0000;
        Map map = new HashMap();
        map.put("scur", scur);
        map.put("tcur", tcur);
        URL += "&scur=" + scur + "&tcur=" + tcur;
        String json = HttpClientUtils.http_post("", URL, null, null, null);
        if (org.apache.commons.lang.StringUtils.isNotEmpty(json)) {
            JSONObject jsonObject = JSON.parseObject(json);
            if(jsonObject.get("result")!=null){
                String result = jsonObject.get("result").toString();
                JSONObject jsonObject2 = JSON.parseObject(result);
                if(jsonObject2.get("rate")!=null){
                    String rateStr = jsonObject2.get("rate").toString();
                    rate = Double.parseDouble(rateStr);
                    System.out.println(scur+"-->"+tcur+":"+rate);
                }
            }
        }
        return rate;
    }

    public static void main(String[] args) {
        double rate = getCurrentRate("USD", "CNY");
        System.out.print("rate:" + rate);
    }
}
